﻿using Framework.Common.SerializeOperation;
using Framework.Redis;
using PaPaPa.Data.EF;
using PaPaPa.Data.Monitors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PaPaPa.Core.Caches
{
    public class RedisCacheCore
    {
        public static void Init()
        {
            RedisSingleton.GetInstance.Client = new Framework.Redis.Client.RedisClient();
            //todo 读取配置连接Redis
            RedisSingleton.GetInstance.Client.Connect("127.0.0.1", 6379);

            //todo 读取数据库加载Redis缓存监视器
            var monitor = new RedisCacheMonitor() { TableName = "User", Fields = new string[] { "Id", "UserName" } };

            MonitorWrapper.Init(monitor);

            //todo 启动时自动加载所有缓存
            LoadUserCache<PaPaPa.Models.Accounts.User>(monitor.Fields);
        }

        private static async void LoadUserCache<T>(params string[] propertyNames)
            where T : class,new()
        {
            List<T> lst = null;

            using (var ef = new DataWrapper<T>())
            {
                lst = await ef.FindAllAsync();
            }

            var type = typeof(T);

            foreach (var user in lst)
            {
                foreach (var propertyName in propertyNames)
                {
                    RedisSingleton.GetInstance.Client.HSet(
                        type.Name,
                        string.Format("{0}:{1}", propertyName, type.GetProperty(propertyName).GetValue(user) as string), user);
                }
            }
        }
    }
}
